import { Component, useState, useEffect, useMemo, useRef } from 'react'
import { View, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'

import './index.scss'
import '../images/public/style.css'

//公共组件

import LgNavCustomBar from '../../components/navCustomBar'
import LgSearch from '../../components/searchInput'
import LgSelepicker from '../../components/selePick'
import LgRefreshPage from '../../components/refreshPage'
import LgButton from '../../components/button'
import LgEmptyContent from '../../components/emptyContent'
//个人组件
import PrNoticeItem from '../components/personal/noticeItem'
import PrLoading from '../components/personal/loading'
import Header from '../components/header';
//工具
import { getStorage, getBrowserController, getNet, getWxSDKParams } from '../../components/utils'
import MyUtils from '../components/personal/utils'
import { allIdentityCodeLib, identityCodeLib, idCodeAdm } from '../utils/Lib'
import getInfo from '../utils/getInfo'
//api
import {
  API_lockerCheck,//锁控
  API_getSchoolSystemInfo,//获取学校及系统信息
  API_getUserInfo,//获取个人信息
  API_getNoticeList,//获取通知列表
  API_delNotice,//删除发布者公告
  API_callbackNotice,//撤回通知
  API_exportNotices //导出公告
} from '../../../network/servers'
import { getSubsystemBySystemId, getUrlBySchoolId } from "../../../network/getSubsystem"
import { getBaseUrl } from '../../../network/baseUrl'
import { transmitUrlToVisit } from '../../../network/proxy'
import NavTabBar from '../components/navTabBar';
import Filter from '../components/filter-popup';
import NoticeCard from '../components/card';
import { useResetDate } from '../../hooks/useRestDate'

import SearchPageComp from '../searchPageComp'

let trigger = 0
interface IndexState {
  isInit: boolean//是否初始化完成

  listDataA: { name: string }[]//下拉框选项列表
  noticeList: any[]//消息信息列表
  noticeList2: any[]//消息信息列表
  searchValue: string//搜索框搜索内容
  onInputValue: string//搜索框输入内容
  allCount: number
  filterVisible: boolean

  noticeStatus: number | ""//消息状态
  pageNum: number,//消息页数
  isFirstEntry: boolean,
  isToSearch: boolean,    //是否是第一次进入这个页面
  h: string // 搜索记录
  // openCheckToken: boolean    //是否开启了token检测
}

var browserController = getBrowserController()
var net = getNet()
// eslint-disable-next-line import/no-commonjs

if (process.env.TARO_ENV === 'weapp') {
  var app = Taro.getApp().$app
} else if (process.env.TARO_ENV === 'h5') {
  var storage = getStorage()
  var browserController = getBrowserController()
  if (getInfo.getEnv() === "weapp") {
    var wx = require('weixin-js-sdk')
  }
}


// if(process.env.NODE_ENV === "development" && process.env.TARO_ENV === 'h5'){
//   const userInfoData = {
//     // "UserID":"zdyyjh",
//     // "SchoolID":"S-3333",
//     // "UserType":0
//   }
//   // const token = "F3663D29-C826-456D-B700-98667A046798"
//   var storage = getStorage()
//   storage.set("userInfo",JSON.stringify(userInfoData))//<=上线要删掉！！！！！！！
//   // storage.set("token",token)
//   // storage.set()
// }
const codeType = {
  200: "成功",
  400: "参数不符逻辑",
  401: "token未认证",
  405: "请求方式不正确",
  500: "系统错误"
}
export default class Index extends Component<any, IndexState> {
  constructor(props) {
    super(props);
    this.state = {
      isInit: false,
      listDataA: [{ name: "全部状态" }, { name: "未发布" }, { name: "已发布" }],
      noticeList: [],
      noticeList2: [],
      allCount: 0,
      filterVisible: false,
      noticeStatus: "",
      searchValue: "",
      onInputValue: "",
      pageNum: 1,
      isFirstEntry: true,
      isToSearch: false,
      h: ''
      // openCheckToken:false,
    };
    this.onEditNotice = this.onEditNotice.bind(this); //编辑通知
    this.onDeleteNotice = this.onDeleteNotice.bind(this); //删除通知
    this.onCallbackNotice = this.onCallbackNotice.bind(this); //撤回通知

    this.onSearch = this.onSearch.bind(this); //搜索框搜索
    this.onSearch2 = this.onSearch2.bind(this); //搜索框搜索
    this.onInput = this.onInput.bind(this); //搜索框输入

    this.changeSele = this.changeSele.bind(this); //下拉框的值改变
    this.openSelepicker = this.openSelepicker.bind(this); //打开下拉框
    this.closeSelepicker = this.closeSelepicker.bind(this); //关闭下拉框
  }

  componentWillMount() {
    if (process.env.TARO_ENV === "h5") {
      if (getInfo.getEnv() === "weapp") {
        //小程序嵌入H5
        getUrlBySchoolId().then((res) => { }); //校园通获取基础平台地址
        getSubsystemBySystemId().then((res) => {
          this.storeEnv();
          this.api_getUserInfo(3);
          // MyUtils.setStorage("schoolSystemInfo", res.data);
          MyUtils.setStorage("baseUrl220", res);
        });
      } else {
        this.storeEnv();
        this.api_getUserInfo(3);
      }
    } else if (process.env.TARO_ENV === "weapp") {
      this.storeEnv();
      this.api_getUserInfo(3);
    }
  }

  componentDidMount() {
    if (trigger > 0) return;
    const noticeType = MyUtils.getQueryVariable("noticeType");
    if (noticeType) {
      let data = {
        noticeType: 2, //1-紧急,2-普通
        noticeId: undefined,
      };
      MyUtils.setStorage("toIssueNotice", data);
      trigger += 1;
      setTimeout(() => {
        Taro.navigateTo({
          url: "/pages/noticeApp/issueNotice/index?noticeNature=" + noticeType,
        });
      }, 1000);
    }
  }

  componentWillUnmount() {
    if (process.env.TARO_ENV === "h5" && getInfo.getEnv() == "weapp") {
      this.initWxSdk();
    }
  }

  componentDidShow() {
    //清空选择对象
    MyUtils.setStorage("ObjectData", []);
    MyUtils.setStorage("searchChooseArr", []);
    if (this.state.isFirstEntry == false) {
      this.setState(
        {
          pageNum: 1,
        },
        () => {
          this.api_getNoticeList();
        }
      );
    } else {
      this.setState({
        isFirstEntry: false,
      });
    }
  }

  componentDidHide() { }

  //返回上一页
  handleBack() {
    this.setState({
      isToSearch: false
    })
    const noticeType = MyUtils.getQueryVariable("noticeType");
    if (noticeType) {
      browserController.goHome();
    } else {
      Taro.navigateBack({
        delta: 1,
      });
    }
  }
  //储存环境（小程序webview嵌入H5环境判断）==========================
  storeEnv() {
    if (process.env.TARO_ENV === "h5") {
      let env = MyUtils.getQueryVariable("env");
      if (env == "weapp") {
        MyUtils.setStorage("env", "weapp", false); //小程序嵌入H5页面
      } else {
        MyUtils.setStorage("env", "h5", false); //app上的h5
      }
    } else {
      MyUtils.setStorage("env", "", false); //微信小程序环境
    }
  }
  //WXsdk注册==========================
  async initWxSdk() {
    const params = await getWxSDKParams(["chooseImage", "previewImage"]);
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log("WxSdk ready");
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log("wxSdk验证失败", res);
    });
  }
  //登录状态验证======================
  checkToken(url) {
    //检查token是否过期
    if (process.env.TARO_ENV === "h5" && getInfo.getEnv() != "weapp") {
      const script = document.createElement("script");
      script.setAttribute("src", `${url}/JS/mobile-check-online.min.js`);
      let token = getInfo.getToken() || MyUtils.getQueryVariable("lg_tk");
      document.head.appendChild(script);
      script.addEventListener("load", () => {
        console.log("启动token校验", url, token, "220");
        (window as any).lgCheckOnline(url, token, "220", (newToken) => {
          console.log("token过期,获取新token:", newToken);
          MyUtils.setStorage("lg_tk", newToken);
        });
      });
    }
  }
  //路由==============================
  toIssueNotice(noticeType, noticeId?: string) {
    //跳转到发布通知公告页
    console.log("跳转到发布通知公告页");
    let data = {
      noticeType, //1-紧急,2-普通
      noticeId: noticeId,
    };
    console.log("toIssueNotice", data);
    MyUtils.setStorage("toIssueNotice", data);
    Taro.navigateTo({
      url: "/pages/noticeApp/issueNotice/index",
    });
  }
  toNoticeDetail(item) {
    console.log("跳转到通知详情页");
    let data = {
      noticeData: item,
    };
    console.log(data)
    MyUtils.setStorage("toNoticeDetail", data);
    Taro.navigateTo({
      url: "/pages/noticeApp/noticeDetail/index",
    });
  }
  goMainPage() {
    //路由-返回webApp首页
    if (process.env.TARO_ENV === "h5") {
      if (browserController) {
        browserController.goHome();
      }
    } else {
      console.log("返回webApp首页函数,只能在webApp生效");
    }
  }
  //api网络请求=======================
  api_getUserInfo(ReRequest = 0) {
    //ReRequest:当请求失败时,可重新请求次数
    let params = {
      token: getInfo.getToken(),
      // schoolId:getInfo.getSchoolId()
    };
    let header = {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: getInfo.getToken(),
    };
    API_getUserInfo(params, header).then((res) => {
      console.log("api-获取个人信息:", res);
      if (res.code == 200) {
        MyUtils.setStorage("userInfo", res.data);
        if (res.data.userType == 2 || res.data.userType == 3) {
          //如果是学生和家长就不给进
          Taro.hideLoading();
          Taro.showToast({
            title:
              res.data.userType == 2
                ? "学生没有发布通知权限"
                : res.data.userType == 3
                  ? "家长没有发布通知权限"
                  : "",
            icon: "none",
            mask: true,
            duration: 1500,
          });
        } else {
          this.api_getSchoolSystemInfo(3); //获取学校信息
        }
      } else {
        if (ReRequest > 0) {
          console.log("[x]个人信息获取失败,重新请求");
          setTimeout(() => {
            this.api_getUserInfo(ReRequest - 1);
          }, 500);
        } else {
          Taro.showToast({
            // title:codeType[res.code],
            title: res.msg,
            icon: "none",
            duration: 2000,
          });
          console.log("[x]个人信息获取失败,不再重新请求");
        }
      }
    });
    // .catch((res)=>{
    //   if(ReRequest > 0){
    //     console.log("[x]个人信息获取失败,重新请求2")
    //     setTimeout(() => {
    //       this.api_getUserInfo(ReRequest-1)
    //     }, 500);
    //   }else{
    //     console.log("[x]个人信息获取失败,不再重新请求")
    //   }
    // })
  }

  api_getSchoolSystemInfo(ReRequest = 0) {
    //ReRequest:当请求失败时,可重新请求次数
    // Taro.showLoading({
    //   title: "加载中",
    //   mask: true,
    // });
    let param = {
      token: getInfo.getToken(),
      // schoolId:getInfo.getSchoolId()
    };
    let header = {
      Authorization: getInfo.getToken(),
    };
    this.api_getNoticeList();
    this.setState({
      isInit: true,
    });
    // API_getSchoolSystemInfo(param, header)
    //   .then((res: any) => {
    //     console.log("api-获取学校及系统信息:", res);
    //     if (res.code == 200) {
    //       if (!res.data.schoolId) {
    //         if (ReRequest > 0) {
    //           console.log("[x]学校信息获取失败,重新请求");
    //           setTimeout(() => {
    //             this.api_getSchoolSystemInfo(ReRequest - 1);
    //           }, 500);
    //         } else {
    //           this.showToast("获取学校信息失败", "none", 2000);
    //           console.log("[x]学校信息获取失败,不再重新请求");
    //           if (process.env.TARO_ENV === "h5") {
    //             setTimeout(() => {
    //               this.goMainPage();
    //             }, 1500);
    //           }
    //         }
    //       } else {
    //         MyUtils.setStorage("schoolSystemInfo", res.data);
    //         this.checkToken(res.data.baseUrl); //开启token校验
    //         this.api_getNoticeList();
    //         this.setState({
    //           isInit: true,
    //         });
    //       }
    //     } else {
    //       Taro.showToast({
    //         title: codeType[res.code],
    //         icon: "none",
    //         duration: 2000,
    //       });
    //     }
    //   })
    //   .catch(() => {
    //     if (ReRequest > 0) {
    //       console.log("[x]学校信息获取失败,重新请求2");
    //       setTimeout(() => {
    //         this.api_getSchoolSystemInfo(ReRequest - 1);
    //       }, 500);
    //     } else {
    //       this.showToast("获取学校信息失败", "none", 2000);
    //       console.log("[x]学校信息获取失败,不再重新请求2");
    //       if (process.env.TARO_ENV === "h5") {
    //         setTimeout(() => {
    //           this.goMainPage();
    //         }, 1500);
    //       }
    //     }
    //   });
  }

  api_getNoticeList() {
    Taro.showLoading({
      title: "加载中",
      mask: true,
    });
    let params = {
      keyword: this.state.searchValue == undefined ? '' : this.state.searchValue, //关键字
      status: this.state.noticeStatus, //公告状态；-1/未发布；0/已结束； 1/进行中；2/已发布(包括已结束和进行中);为空默认全部
      // userId: getInfo.getUserId(), //为空则显示全部
      sysId: "", //为空则显示全部
      eduId: getInfo.getSchoolId(),
    };
    let pageNum = this.state.pageNum;
    let pageSize = 10;
    let header = {
      Authorization: getInfo.getToken(),
    };
    API_getNoticeList(params, pageNum, pageSize, header)
      .then((res) => {
        console.log("API-获取公告信息列表:", res, "\nparams:", params);
        if (res.code == 200) {
          if (res.data.length == 0) {
            this.showToast("已获取全部数据", "none", 2000);
            if (pageNum == 1) {
              this.setState(
                {
                  noticeList: [],
                  pageNum: 1,
                  allCount: res.total
                },
                () =>
                  console.log(
                    "noticeList:",
                    this.state.noticeList,
                    "\npageNum:",
                    pageNum
                  )
              );
            } else {
              this.setState(
                {
                  pageNum: this.state.pageNum - 1,
                  allCount: res.total
                },
                () =>
                  console.log(
                    "noticeList:",
                    this.state.noticeList,
                    "\npageNum:",
                    pageNum
                  )
              );
            }
          } else {
            Taro.hideLoading();
            if (pageNum == 1) {
              this.setState(
                {
                  noticeList: res.data,
                  allCount: res.total
                },
                () =>
                  console.log(
                    "noticeList:",
                    this.state.noticeList,
                    "\npageNum:",
                    pageNum
                  )
              );
            } else {
              this.setState(
                {
                  noticeList: [...this.state.noticeList, ...res.data],
                  allCount: res.total
                },
                () =>
                  console.log(
                    "noticeList:",
                    this.state.noticeList,
                    "\npageNum:",
                    pageNum
                  )
              );
            }
          }
        } else {
          this.showToast(codeType[res.code], "none", 2000);
        }
      })
      .catch(() => {
        this.showToast("获取公告列表失败", "none", 2000);
        console.log("[x]公告列表,获取失败");
      });
  }
  api_getNoticeList2(h) {
    if (!h) {
      return
    }
    Taro.showLoading({
      title: "加载中",
      mask: true,
    });
    let params = {
      keyword: h, //关键字
      status: this.state.noticeStatus, //公告状态；-1/未发布；0/已结束； 1/进行中；2/已发布(包括已结束和进行中);为空默认全部
      // userId: getInfo.getUserId(), //为空则显示全部
      sysId: "", //为空则显示全部
      eduId: getInfo.getSchoolId(),
    };
    let pageNum = this.state.pageNum;
    let pageSize = 10;
    let header = {
      Authorization: getInfo.getToken(),
    };
    API_getNoticeList(params, pageNum, pageSize, header)
      .then((res) => {
        console.log("API-获取公告信息列表:", res, "\nparams:", params);
        if (res.code == 200) {
          if (res.data.length == 0) {
            this.showToast("已获取全部数据", "none", 2000);
            if (pageNum == 1) {
              this.setState(
                {
                  noticeList2: [],
                  pageNum: 1,
                },
                () =>
                  console.log(
                    "noticeList2:",
                    this.state.noticeList2,
                    "\npageNum:",
                    pageNum
                  )
              );
            } else {
              this.setState(
                {
                  pageNum: this.state.pageNum - 1,
                },
                () =>
                  console.log(
                    "noticeList2:",
                    this.state.noticeList2,
                    "\npageNum:",
                    pageNum
                  )
              );
            }
          } else {
            Taro.hideLoading();
            if (pageNum == 1) {
              this.setState(
                {
                  noticeList2: res.data,
                },
                () =>
                  console.log(
                    "noticeList2:",
                    this.state.noticeList2,
                    "\npageNum:",
                    pageNum
                  )
              );
            } else {
              this.setState(
                {
                  noticeList2: [...this.state.noticeList2, ...res.data],
                },
                () =>
                  console.log(
                    "noticeList2:",
                    this.state.noticeList2,
                    "\npageNum:",
                    pageNum
                  )
              );
            }
          }
        } else {
          this.showToast(codeType[res.code], "none", 2000);
        }
      })
      .catch(() => {
        this.showToast("获取公告列表失败", "none", 2000);
        console.log("[x]公告列表,获取失败");
      });
  }
  //下拉刷新&下拉加载==================
  onPull() {
    console.log("上拉加载");
    let pageNum = this.state.pageNum;
    this.setState(
      {
        pageNum: pageNum + 1,
      },
      () => {
        this.api_getNoticeList();
      }
    );
  }
  onDown() {
    console.log("下拉刷新");
    this.setState(
      {
        pageNum: 1,
      },
      () => {
        this.api_getNoticeList();
      }
    );
  }
  //搜索框============================
  onSearch(value) {
    console.log("onSearch", value);
    this.setState(
      {
        searchValue: value,
        isToSearch: true,
        noticeList2: []
      },
      // () => {
      //   this.api_getNoticeList();
      // }
    );
    // Taro.navigateTo({
    //   url: "/pages/noticeApp/searchPageComp/index",
    // });
  }
  onSearch2(h) {
    console.log("onSearch", h);
    this.setState({
      h: h
    })
    this.api_getNoticeList2(h);
  }
  onInput(value) {
    console.log("onInput", value);
    this.setState({
      onInputValue: value,
    });
  }
  //下拉框============================
  changeSele(data, i) {
    //i：0-全部，1-未发布，2-已发布
    console.log("下拉框", data, i);
    this.setState(
      {
        noticeStatus: i == 0 ? "" : i == 1 ? 0 : 1,
        pageNum: 1,
      },
      () => {
        this.api_getNoticeList();
      }
    );
  }
  openSelepicker() {
    //打开下拉框
  }
  closeSelepicker() {
    //关闭下拉框
  }
  //消息事件处理================================
  onEditNotice(noticeId, noticeType, timeType) {
    //编辑消息
    console.log("编辑消息", noticeId);
    if (noticeType == 1) {
      //紧急通知
      if (!this.haveEmergencyNotice()) {
        Taro.showToast({
          title: "无编辑紧急通知权限",
          icon: "none",
          duration: 2000,
        });
        return;
      }
    }
    if (timeType == 1) {
      //定时消息
      Taro.showToast({
        title: "定时通知请前往PC端编辑",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    this.toIssueNotice(1, noticeId);
  }
  onDeleteNotice(noticeId, noticeType, timeType) {
    //删除消息
    if (noticeType == 1) {
      if (!this.haveEmergencyNotice()) {
        Taro.showToast({
          title: "无删除紧急通知权限",
          icon: "none",
          duration: 2000,
        });
        return;
      }
    }
    if (timeType == 1) {
      //定时消息
      Taro.showToast({
        title: "定时通知请前往PC端删除",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    let that = this;
    Taro.showModal({
      title: "提示",
      content: "确定要删除该通知吗？",
      success: function (res) {
        if (res.confirm) {
          //用户点击确定
          let params = {
            noticeId,
            schoolId: getInfo.getSchoolId(),
          };
          let header = {
            "Content-Type": "application/x-www-form-urlencoded",
            Authorization: getInfo.getToken(),
          };
          API_delNotice(params, header)
            .then((res) => {
              if (res.code == 200) {
                that.showToast("删除成功", "success", 2000);
                that.setState(
                  {
                    pageNum: 1,
                  },
                  () => {
                    that.api_getNoticeList(); //重新请求列表
                  }
                );
              } else {
                that.showToast("删除失败1", "none", 2000);
              }
            })
            .catch(() => {
              that.showToast("删除失败2", "none", 2000);
            });
        } else if (res.cancel) {
          //用户点击取消
        }
      },
    });
  }
  onCallbackNotice(noticeId, noticeType) {
    //撤回消息
    if (noticeType == 1) {
      if (!this.haveEmergencyNotice()) {
        Taro.showToast({
          title: "无撤回紧急通知权限",
          icon: "none",
          duration: 2000,
        });
        return;
      }
    }
    let that = this;
    Taro.showModal({
      title: "提示",
      content: "确定要撤回该通知吗？",
      success: function (res) {
        if (res.confirm) {
          //用户点击确定
          let params = {
            noticeId,
            schoolId: getInfo.getSchoolId(),
          };
          let header = {
            "Content-Type": "application/x-www-form-urlencoded",
            Authorization: getInfo.getToken(),
          };
          API_callbackNotice(params, header)
            .then((res) => {
              if (res.code == 200) {
                that.showToast("撤回成功", "success", 2000);
                that.api_getNoticeList(); //重新请求列表
              } else {
                that.showToast("撤回失败", "none", 2000);
              }
            })
            .catch(() => {
              that.showToast("撤回失败", "none", 2000);
            });
        }
      },
    });
  }
  //判断是否有修改紧急通知权限================
  haveEmergencyNotice() {
    let identityCode = getInfo.getIdentityCode();
    let identityInfos = MyUtils.getStorage("userInfo").identityInfos;
    if (
      identityInfos?.findIndex((item) => item.identityCode == identityCode) == -1
    ) {
      console.log("个人身份列表中不存在该身份", identityCode);
      identityCode = identityInfos[0].identityCode;
    }

    if (idCodeAdm.findIndex((item) => item == identityCode) != -1) {
      //有发布紧急通知权限
      console.log("当前身份:", identityCode, "是否有发布紧急通知权限:是");
      return true;
    } else {
      console.log("当前身份:", identityCode, "是否有发布紧急通知权限:否");
      return false;
    }
  }
  //taro弹窗================================
  showToast(title, icon, duration, mask = false) {
    Taro.hideLoading();
    setTimeout(() => {
      Taro.showToast({
        title: title,
        icon: icon,
        duration: duration,
        mask: mask,
      });
    }, 500);
  }
  //=================================
  replaceHost = (url) => {
    //替换外网IP或域名
    let baseUrl = MyUtils.getStorage("baseUrl220", true);
    console.log("baseUrl", baseUrl);
    if (!baseUrl) {
      return url;
    }
    let hostOfBaseUrl: any = MyUtils.parseUrl(baseUrl);
    let newUrl = MyUtils.replaceHostOfUrl(
      url,
      hostOfBaseUrl.host,
      hostOfBaseUrl.port
    );
    return newUrl;
  };

  getFileName = (fileName: string) => {
    if (!fileName) {
      return "文件";
    }

    let pot1 = fileName.lastIndexOf(".");
    return fileName.substring(0, pot1);
  };

  /* 导出我发布的所有通知 */
  exportNotices = () => {
    let url = `${getBaseUrl()}/api/notice/excel/export/user/released?schoolId=${getInfo.getSchoolId()}&userId=${getInfo.getUserId()}`;

    let header = {
      Authorization: getInfo.getToken(),
    };

    if (getInfo.getEnv() === "weapp") {
      url = transmitUrlToVisit(url);
    }

    let fileName = `我发布的通知.xlsx`;
    let that = this;

    Taro.showModal({
      title: "提示",
      content: "即将导出所有通知并直接预览",
      confirmColor: "#0099ff",
      success: function (res) {
        if (res.confirm) {
          Taro.showLoading({
            title: "导出中...",
          });
          Taro.downloadFile({
            url,
            header,
            success: (result) => {
              if (result.statusCode == 200) {
                let path = result.tempFilePath;
                let downloadFileUrl =
                  getBaseUrl() + 'edu-office-platform' + "/api/commons/file/upload";
                // getBaseUrl() + "/api/commons/file/mobile/batch/upload";
                if (getInfo.getEnv() === "weapp") {
                  downloadFileUrl = transmitUrlToVisit(downloadFileUrl);
                }
                Taro.uploadFile({
                  url: downloadFileUrl,
                  filePath: path,
                  fileName,
                  name: "file",
                  header,
                  success: (res1) => {
                    let data = JSON.parse(res1.data);
                    let fileUrl = data.data[0].url;

                    Taro.hideLoading();
                    if (getInfo.getEnv() === "weapp") {
                      let name = that.getFileName(data.data[0].name);
                      let suffix = MyUtils.getSuffix(path);

                      console.log(that.replaceHost(fileUrl), name, suffix);
                      try {
                        browserController.openFileForWebview(wx, {
                          fileUrl: that.replaceHost(fileUrl),
                          fileType: "xlsx",
                          fileName: "我发布的通知",
                        });
                      } catch (err) {
                        console.log(err);
                        Taro.showToast({ title: err, icon: "none" });
                      }
                      return;
                    } else {
                      net.downloadFile({
                        url: fileUrl,
                        fileName,
                        onProgress: (process) => {
                          Taro.showToast({
                            icon: "loading",
                            title: `正在下载${process}%`,
                          });
                        },
                        onSuccess: (filePath) => {
                          browserController.openFileReader(filePath); //下载完就预览
                        },
                        onError: (error) => {
                          Taro.showToast({
                            title: "下载失败请联系管理员" + error,
                            icon: "none",
                            duration: 2000,
                          });
                        },
                      });
                    }
                  },
                });
              }
            },
          });
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  };

  getAction(item) {
    console.log(item)
    const { status, noticeId, noticeType, timeType } = item
    if (process.env.TARO_ENV === "h5") {
      if (status == 1) {//已发布
        // return []
        return [{
          text: "撤回",
          onClick: () => this.onCallbackNotice(noticeId, noticeType),
          key: "callback",
        }]
      } else if (status == 0) {//未发布
        return [{
          text: "编辑",
          onClick: () => this.onEditNotice(noticeId, noticeType, timeType),
          key: "edit",
        }, {
          text: "删除",
          onClick: () => this.onDeleteNotice(noticeId, noticeType, timeType),
          key: "delete",
        }]
      } else {
        return []
      }
    } else if (process.env.TARO_ENV === 'weapp') {
      if (status == 1) {//进行中
        // return []
        return [{
          text: "撤回",
          onClick: () => this.onCallbackNotice(noticeId, noticeType),
          key: "callback",
        }]
      } else if (status == 0) {//未发布
        return [{
          text: "编辑",
          onClick: () => this.onEditNotice(noticeId, noticeType, timeType),
          key: "edit",
        }, {
          text: "删除",
          onClick: () => this.onDeleteNotice(noticeId, noticeType, timeType),
          key: "delete",
        }]
      } else {
        return []
      }
    }
  }

  childenDom = () => {
    console.log(this.state.noticeList2)
    return (
      <View>
        {
          this.state.noticeList2.length > 0 ? this.state.noticeList2.map(i => {
            console.log(i.title.indexOf(this.state.h))
            let indexH = i.title.indexOf(this.state.h)
            return (
              <View onClick={() => {this.toNoticeDetail(i)}} className='itemList'>{i.title.slice(0,indexH)} <span style={{color: '#ff7d27'}}>{i.title.slice(indexH, indexH + this.state.h.length)}</span> {i.title.slice(indexH + this.state.h.length)}</View>
            )
          }) : ''
        }
      </View>
    )
  }

  render() {
    let isInit = this.state.isInit;
    if (!isInit) {
      return (
        <PrLoading
          isOpened={!isInit}
          mode="center"
          content="加载中..."
        ></PrLoading>
      );
    }
    let noticeList = this.state.noticeList;
    let searchValue = this.state.searchValue;
    let haveEmergencyNotice = this.haveEmergencyNotice();
    let env = getInfo.getEnv();

    let allCount = this.state.allCount
    let filterVisible = this.state.filterVisible

    let statusList = this.state.listDataA.map((l, i) => ({ name: l.name, key: i }))
    const noticeStatus = this.state.noticeStatus

    const noticeStatusKey = noticeStatus === "" ? 0 : noticeStatus == 0 ? 1 : 2

    return (
      <View className="index">
        {env === "weapp" ? (
          ""
        ) : (
          <LgNavCustomBar
            mainTitle={"部门通知"}
            needMainIcon={process.env.TARO_ENV === "h5" ? true : false}
            needBackIcon={process.env.TARO_ENV === "h5" ? true : false}
            isTitlePositionLeft={false}
            mainTitleBold={true}
            onClick={this.handleBack}
          ></LgNavCustomBar>
        )}

        <NavTabBar
          infoTagDom={
            <View>
              共<Text>{allCount}</Text>
              条通知
            </View>
          }
          // isOpen={filterVisible}
          // onInput={this.onInput}
          // onConfirm={this.onSearch}
          setIsOpen={(isOpen) => this.setState({ filterVisible: isOpen })}
          onClick={this.onSearch}
        />

        {
          this.state.isToSearch ?
            <SearchPageComp
             setDataList={() => {
              this.setState({
                noticeList2: []
              })
            }}
            placeholder={'搜索部门通知标题'}
            visible={false}
             dataList={this.state.noticeList2} 
             loading={false} 
             childrenDom={this.childenDom()}
              setVisible={() => {
              this.setState(
                {
                  isToSearch: false
                }
              )
            }} setWords={(h) => { this.onSearch2(h)}}></SearchPageComp> : ''
        }


        <LgRefreshPage
          className="index_RefreshPage"
          onPull={this.onPull.bind(this)}
          onDown={this.onDown.bind(this)}
          downText={["下拉刷新", "释放刷新"]}
          pullText={["上拉加载", "释放加载"]}
        >
          <View className="index_contentBox">
            {noticeList.map((item, index) => {
              console.log(item)
              const { content, noticeId, title, status, releaseTime, userName } = item;
              const actions = this.getAction(item);
              const { unit, value } = useResetDate(releaseTime);
              const subtitle = releaseTime ? `${value}${unit}前${userName}发布` : "";
              return (
                <View className="notice_item_wrapper">
                  <NoticeCard
                    title={title}
                    info={item}
                    subtitle={subtitle}
                    status={status}
                    content={content}
                    actions={actions}
                    onClick={() => {
                      item.status == 1 ? this.toNoticeDetail(item) : this.onEditNotice(item.noticeId, item.noticeType, '')
                    }}
                  />
                </View>
              );
            })}
            {noticeList.length == 0 ? (
              <View className="No_content">
                <LgEmptyContent
                  // imgUrl={require("../images/index/占位图.png")}
                  text={
                    searchValue
                      ? `未搜索到“${searchValue}”相关内容`
                      : "暂无信息"
                  }
                  type="B"
                ></LgEmptyContent>
              </View>
            ) : (
              ""
            )}
          </View>
        </LgRefreshPage>

        <Filter
          isOpen={filterVisible}
          setIsOpen={(value) => this.setState({ filterVisible: value })}
          dataList={[statusList]}
          statusList={[noticeStatusKey]}
          setStatusFns={[(key) => this.changeSele("", key)]}
        />

        {/* <View className="index_btnBox"> */}
        <View>
          <View className='create' onClick={() => { this.toIssueNotice(2) }}></View>
          <i className='create-shadow'></i>
        </View>


        <><View className='create' onClick={() => { this.toIssueNotice(2) }}></View>
          <i className='create-shadow'></i></>


        {/* <View className='export_btn' onClick={() => this.exportNotices()}>
          导出
        </View> */}
      </View>
    );
  }
}
